package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @创建人: 放生
 * @创建时间: 2021/7/16
 * @描述:
 */
public class FangshengApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();//单列池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();//单列池
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public FangshengApplicationContext(Class configClass) {
        this.configClass = configClass;
        // 解析配置类
        //ComponentScan 注解---->扫描路径---->扫描--->创建beanDefinition---->beanDefinitionMap
        scan(configClass);
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);//单列bean
                singletonObjects.put(beanName, bean);
            }

        }


    }

    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value();//扫描路径
        System.out.println(path);
        path = path.replace(".", "/");
        // 根据上一步拿到的路径，扫描
        //扫描
        //Bootstrap-----> jre/lib
        //Ext--------> jre/ext/lib
        //App---------> classpath---->
        ClassLoader classLoader = FangshengApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {

                    String className = fileName.substring(fileName.indexOf("com"), fileName.lastIndexOf(".class"));
                    className = className.replace("\\", ".");

                    try {
                        Class<?>  aClass = classLoader.loadClass(className);
                        if (aClass.isAnnotationPresent(Component.class)) {

                            if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                BeanPostProcessor instance = (BeanPostProcessor) aClass.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }

                            //表示当前类是一个bean
                            //解析类判断当前的bean是一个单列的还是原型的bean
                            Component componentAnnotation = aClass.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setaClass(aClass);
                            if (aClass.isAnnotationPresent(Scop.class)) {
                                Scop scopeAnnotation = aClass.getDeclaredAnnotation(Scop.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            } else {
                                //就是你一个单列bean
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object o = singletonObjects.get(beanName);
                return o;
            } else {

                //创建bean
                Object bean = createBean(beanName, beanDefinition);
                return bean;
            }
        } else {
            //不存在对应的bean
            throw new NullPointerException();
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class aClass = beanDefinition.getaClass();
        try {
            Object instance = aClass.getDeclaredConstructor().newInstance();
            //依赖注入
            for (Field declaredField : aClass.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowrid.class)) {
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance, bean);
                }
            }
            //Aware 回调
            if (instance instanceof BeanNameAware) {//只要实现了BeanNameAware 这个接口的类
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            //初始化前的操作
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }
            //初始化
            if (instance instanceof InitializingBean) {//只要实现了BeanNameAware 这个接口的类
                ((InitializingBean) instance).afterPropertiesSet();
            }
            //初始化后的操作
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }


            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
